package com.hgc.ch01.pool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by 01367627 on 2019/6/27.
 */
public class DBPoolTest {

    static DBPool dbPool = new DBPool(1);
    static CountDownLatch start = new CountDownLatch(1);
    static CountDownLatch end;

    static class MyRunnable implements Runnable{
        int count;
        AtomicInteger got;
        AtomicInteger notGot;

        public MyRunnable(int count,AtomicInteger got,AtomicInteger notGot){
            this.count = count;
            this.got = got;
            this.notGot = notGot;
        }

        public void run() {
            try {
                start.await();
            } catch (Exception ex) {

            }
            while (count > 0) {
                try {
                    // 从线程池中获取连接，如果1000ms内无法获取到，将会返回null
                    // 分别统计连接获取的数量got和未获取到的数量notGot
                    System.out.println(Thread.currentThread().getName() + "尝试中：" + count);
                    Connection connection = dbPool.fetchConnection(100L);
                    PreparedStatement pst;
                    if (connection != null) {
                        try {
                            pst = connection.prepareStatement("insert into t_user(name) values ('张三" + got + "')");
                            pst.executeUpdate();
                            pst.close();
                            connection.commit();
                        }  finally {
                            dbPool.releaseConnection(connection);
                            got.incrementAndGet();
                        }
                    } else {
                        notGot.incrementAndGet();
                    }
                } catch (Exception ex) {
                } finally {
                    count--;
                }
            }
            end.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        // 线程数量，可以线程数量进行观察
        int threadCount = 50;
        end = new CountDownLatch(threadCount);
        int count = 20;
        AtomicInteger got = new AtomicInteger();
        AtomicInteger notGot = new AtomicInteger();
        for (int i = 0; i < threadCount; i++) {
            Thread thread = new Thread(new MyRunnable(count, got, notGot), "ConnectionRunnerThread" + i);
            thread.start();
        }
        start.countDown();
        end.await();
        System.out.println("total invoke: " + (threadCount * count));
        System.out.println("got connection:  " + got);
        System.out.println("not got connection " + notGot);
    }

}
